﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.RoomAggregate;
using MediatR;

namespace Gym.Application.Rooms.Commands.CreateRoom
{
    public class CreateRoomCommandHandler : IRequestHandler<CreateRoomCommand, ErrorOr<Room>>
    {
        private readonly ISubscriptionsRepository _subscriptionsRepository;
        private readonly IGymsRepository _gymsRepository;

        public CreateRoomCommandHandler(
            ISubscriptionsRepository subscriptionsRepository,
            IGymsRepository gymsRepository)
        {
            _subscriptionsRepository = subscriptionsRepository;
            _gymsRepository = gymsRepository;
        }
        public async Task<ErrorOr<Room>> Handle(CreateRoomCommand request, CancellationToken cancellationToken)
        {
            var gym = await _gymsRepository.GetByIdAsync(request.GymId);

            if (gym is null)
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            var subscription = await _subscriptionsRepository.GetByIdAsync(gym.SubscriptionId);
            if (subscription is null)
            {
                return Error.Unexpected(description: "没有找到该订阅信息");
            }

            var room = new Room(
                name: request.RoomName,
                maxDailySessions: subscription.GetMaxDailySessions(),
                gymId: request.GymId);

            var addGymResult = gym.AddRoom(room);
            
            if (addGymResult.IsError)
            {
                return addGymResult.Errors;
            }

            await _gymsRepository.UpdateAsync(gym);

            return room;
        }
    }
}
